package com.zhuhjay.common.base.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.zhuhjay.common.base.exception.BasicBusinessException;
import com.zhuhjay.common.base.exception.ServerErrorException;
import com.zhuhjay.common.base.model.domain.MailTemplate;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

/**
 * 邮件发送工具类
 * @author ZhuHJay
 * @date 2023/3/13 15:27
 */
@Slf4j
public class MailSenderUtils {

    /**
     * 邮件发送人账户
     */
    private static final MailAccount MAIL_ACCOUNT;
    /**
     * 邮箱是否可以使用
     */
    private static boolean mailEnable = true;
    /**
     * 邮件模板
     */
    private static final String EMAIL_DEFAULT_TEMPLATE = "email-default.ftl";
    /**
     * 邮件模板
     */
    private static final Template EMAIL_TEMPLATE;

    static {
        MAIL_ACCOUNT = SpringContextHolder.getBean(MailAccount.class);
        // 开启SSL加密
        MAIL_ACCOUNT.setSslEnable(true);
        // 开启认证
        MAIL_ACCOUNT.setAuth(true);
        // 如果 from 为空，那么默认邮箱不能使用
        if (StrUtil.isBlank(MAIL_ACCOUNT.getFrom())) {
            mailEnable = false;
        }
        Configuration config = SpringContextHolder.getBean(Configuration.class);
        try {
            EMAIL_TEMPLATE = config.getTemplate(EMAIL_DEFAULT_TEMPLATE);
        } catch (IOException e) {
            throw new ServerErrorException("邮件模板加载失败", e);
        }
    }

    /**
     * 发送邮件(HTML内容)
     */
    public static void sendHtml(MailTemplate mailTemplate) {
        checkEnable();
        try {
            StringWriter writer = new StringWriter();
            Map<String, Object> dataMap = BeanUtil.beanToMap(mailTemplate);
            EMAIL_TEMPLATE.process(dataMap, writer);
            MailUtil.send(
                    MAIL_ACCOUNT, mailTemplate.getTo(),
                    mailTemplate.getSubject(), writer.toString(), true
            );
            writer.close();
        } catch (Exception e) {
            log.error("邮件发送出现问题 {}", e.getMessage());
            throw new BasicBusinessException("邮件发送失败, 请稍后重试");
        }
    }

    /** 邮箱是否可用 */
    private static void checkEnable() {
        if (!mailEnable) {
            log.error("邮箱未配置, 请检查配置文件 {}", MAIL_ACCOUNT);
            throw new BasicBusinessException("邮件发送功能不可用");
        }
    }

    @Getter
    public enum MailSubject {
        /**
         * 主题
         **/
        BIND_EMAIL("绑定邮箱"),
        UNBIND_EMAIL("解绑邮箱"),
        RESET_PASSWORD("重置密码"),
        ;

        private final String subject;

        MailSubject(String subject) {
            this.subject = subject;
        }
    }

}
